import React, { useEffect, useState } from 'react';
import mqtt from 'mqtt';

const MqttComponent = () => {
  const [messages, setMessages] = useState([]);

  // 假设的MQTT服务器地址
  const brokerUrl = 'tcp://172.16.5.234:1883';

  // MQTT客户端实例
  let client;

  // 规则引擎：简单的规则检查函数
  const ruleEngine = (topic, message) => {
    // 假设的规则：如果消息内容包含'alert'，则打印一条消息
    if (message.toString().includes('alert')) {
      console.log(`Alert detected for topic: ${topic}`);
    }
  };

  // 连接MQTT服务器
  const connectMqtt = () => {
    client = mqtt.connect(brokerUrl);

    client.on('connect', () => {
      console.log('Connected to MQTT broker');
      // 订阅主题
      client.subscribe('imilab/e1f0ba2a1ab1b7146569a21340441e55/thing/model/app/get_response', {
        qos: 2,
      });
    });

    client.on('message', (topic, message) => {
      // 更新消息列表
      setMessages((prevMessages) => [...prevMessages, { topic, message: message.toString() }]);
      // 调用规则引擎
      ruleEngine(topic, message);
    });

    client.on('error', (error) => {
      console.error('MQTT error:', error);
    });

    client.on('close', () => {
      console.log('Disconnected from MQTT broker');
    });
  };

  // 发送MQTT消息
  const publishMessage = () => {
    // 这里只是示例，你可能需要用户输入或其他方式生成消息
    const message = 'Hello, MQTT!';
    client.publish('imilab/e1f0ba2a1ab1b7146569a21340441e55/thing/model/app/get', message);
  };

  useEffect(() => {
    connectMqtt();
    return () => {
      if (client) {
        client.end();
      }
    };
  }, []);

  return (
    <div>
      <h2>MQTT Demo</h2>
      <button onClick={publishMessage}>Publish Message</button>
      <ul>
        {messages.map((message, index) => (
          <li key={index}>
            Topic: {message.topic}, Message: {message.message}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default MqttComponent;
